package IO.filesystem;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/* Copy a file or a directory*/
public class Copier {

	File srcFile;
	File desFile;
	String desPath;

	public Copier(String src, String desFolder) {
		srcFile = new File(src);
		desFile = new File(desFolder + "\\" + srcFile.getName());
		if (!desFile.isDirectory()) desFile.mkdirs();
//		prepareCopy();
	}

	void copyFile(File src, String des) {

		if (!src.exists()) {
			System.out.println("File " + src + " does not exist !!!");
			return;
		}

		// always overwrite new file

		try {
			FileInputStream in = new FileInputStream(src);
			FileOutputStream out = new FileOutputStream(new File(des));

			int buff; // 4 bytes buffer
			while ((buff = in.read()) != -1)
				out.write(buff);

			in.close();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/*
	 * Create destination folder
	 */
	public void prepareCopy() {
		// change name when copy on the same folder
		if (srcFile.getAbsolutePath().equals(desFile.getAbsolutePath())) {
			if (srcFile.isFile()) {
				String filename = srcFile.getName();
				int lastPoint = filename.lastIndexOf('.');
				
				if (lastPoint > 0){
					String name = filename.substring(0, lastPoint);
					String ext = filename.substring(lastPoint + 1);
					
					desFile = new File(srcFile.getParentFile().getAbsolutePath() + "\\" + name + "-copy." + ext);
				} else {
					desFile = new File(desFile.getAbsolutePath() + "-copy");
				}
				
			} else if (srcFile.isDirectory()) {
				desFile = new File(desFile.getAbsolutePath() + "-copy");
				if (!desFile.exists()) desFile.mkdir();
			}
		}

		desPath = desFile.getAbsolutePath();
//		System.out.println(srcFile.getAbsolutePath());
//		System.out.println(desFile.getAbsolutePath());
//		System.out.println(desPath);
	}
	
	/*
	 * Recursive copy
	 * */
	private void copyDirectory(File src) {
		for (String subPath : src.list()) {
			File subFile = new File(src.getAbsoluteFile() + "\\" + subPath);
			if (subFile.isFile()) {
				System.out.println("Copy: " + subFile.getName());
				copyFile(subFile, desPath + "\\" + subFile.getName());
			} else if (subFile.isDirectory()){
				desPath += "\\" + subFile.getName();
				new File(desPath).mkdir();
				
				File nsrc = new File(subFile.getAbsolutePath());
				copyDirectory(nsrc);
				desPath = desPath.substring(0, desPath.lastIndexOf('\\'));
			}
			
			
		}
	}

	public void copy(){
		prepareCopy();
		if (srcFile.isFile()) copyFile(srcFile, desFile.getAbsolutePath());
		else if (srcFile.isDirectory()) {
			copyDirectory(srcFile);
		}
	}

	public static void main(String[] args) {
		String srcPath = "D:/minh";
		String desPath = "D:/Download";
		
		Copier copier = new Copier(srcPath, desPath);

		copier.copy();
	}
}
